package com.yukh.framework.iso8583;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;

import org.jpos.iso.ISOException;
import org.jpos.iso.ISOMsg;
import org.jpos.tlv.TLVList;

import com.yukh.framework.util.StringUtil;


public class Iso8583Operator {
	
	public static boolean setTLVField(ISOMsg isoMsg, int fieldNo, TLVList tlvList){
		if (tlvList == null){
			return false;
		}
		try {
			isoMsg.set(fieldNo, tlvList.pack());
		} catch (ISOException e) {
			e.printStackTrace();
		}

		return true;
	}
	public static boolean setField(ISOMsg isoMsg, int fieldNo, String value) {
		if (value == null) {
			return false;
		}

		try {
			isoMsg.set(fieldNo, value);
		} catch (ISOException e) {
			e.printStackTrace();
		}

		return true;
	}

	public static boolean setField(ISOMsg isoMsg, int fieldNo, String pattern, BigDecimal value) {
		if (value == null) {
			return false;
		}

		String sValue = StringUtil.format(pattern, value);
		setField(isoMsg, fieldNo, sValue);

		return true;
	}

	public static boolean setField(ISOMsg isoMsg, int fieldNo, byte[] value) {
		if (value == null) {
			return false;
		}

		try {
			isoMsg.set(fieldNo, value);
		} catch (ISOException e) {
			e.printStackTrace();
		}

		return true;
	}

	public static String getFieldString(ISOMsg isoMsg, int fieldNo) {
		return StringUtil.parseToString(isoMsg.getString(fieldNo));
	}

	public static BigDecimal getFieldBigDecimal(ISOMsg isoMsg, int fieldNo) {
		String sValue = getFieldString(isoMsg, fieldNo);
		if (sValue == null) {
			return null;
		}

		return new BigDecimal(sValue);
	}
	

	public static void checkFieldInfo(int fieldNo, String txnBodyValue, String iso8583FieldValue) {
		if (txnBodyValue.equals(iso8583FieldValue) == false) {
			System.out.println(" + txnBodyValue + ");
		}
	}

	public static void checkFieldInfo(int fieldNo, BigDecimal txnBodyValue,
			BigDecimal iso8583FieldValue) {
		if (txnBodyValue.compareTo(iso8583FieldValue) != 0) {
			System.out.println(" + txnBodyValue + ");
		}
	}

	public static void checkFieldInfo(int fieldNo, Date txnBodyValue, Date iso8583FieldValue) {
		if (iso8583FieldValue != null) {
			Calendar txnBodyCal = Calendar.getInstance();
			txnBodyCal.setTime(txnBodyValue);
			txnBodyCal.set(Calendar.MILLISECOND, 0);

			Calendar iso8583FieldCal = Calendar.getInstance();
			iso8583FieldCal.setTime(iso8583FieldValue);
			iso8583FieldCal.set(Calendar.MILLISECOND, 0);

			if (txnBodyCal.getTimeInMillis() != iso8583FieldCal.getTimeInMillis()) {
				System.out.println(" + txnBodyValue + ");
			}
		} else {
			if (txnBodyValue != null) {
				System.out.println(" + txnBodyValue + ");
			}
		}
	}
}
